<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class UserGroup extends Model
{
    use HasFactory;
    use HasDateTimeFormatter;


    public static $cache_prefix = 'DISPATCH_CACHE_KEY_';

    public static function getDispatchCache($date)
    {
        $key = static::$cache_prefix;
        return Cache::get("$key$date");
    }

    /**
     * 通过 日期+客服列表 生成 该客服的 CacheKey
     * @param $userList Collection
     * @param $date     string
     * @return array|null
     */
    public static function getUserCacheKey($userList, $date)
    {
        return $userList->map(function ($user) use ($date) {
            return "$date.{$user->id}";
        })->toArray();
    }

    /**
     * 获取 当天客服的 CacheKey
     * @param $userList Collection
     * @return array|null
     */
    public static function todayUserCacheKey($userList)
    {
        $date = Carbon::today()->toDateString();
        return static::getUserCacheKey($userList, $date);
    }

    /**
     * 获取 客服当天的已分配数量
     * @param $userList Collection
     * @return array
     */
    public static function getTodayDispatchCache($userList)
    {
        $keys = static::todayUserCacheKey($userList);
        return Cache::get($keys);
    }

    /**
     * Relation 方法
     * 🔗 连接 Administrator.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users()
    {
        return $this->belongsToMany(Administrator::class, 'groups_has_user', 'group_id', 'user_id');
    }

    /**
     * 获取 分组中 在线的 用户
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getGroupOnlineUser()
    {
        return $this->users()->select([
            'id',
            'online',
            'dispatch_limit',
            'order',
        ])
            ->where('online', 1)
            ->orderBy('order')
            ->get();
    }

    /**
     * 获取下一个 可分配的用户
     * 分配条件:
     *  1 . 在线
     *  2 . 不超过设置的用户上限
     *
     * 分配顺序:
     *  1 . 判断上次分配时间,按照距离上次分配时间最久的或者未参与过的来分配
     *
     * @return null|Administrator
     */
    public function dispatchOnlineUser()
    {
        $userList = $this->getGroupOnlineUser();
        $today = today()->toDateString();
        $cacheList = static::getTodayDispatchCache($userList);
        $data = $userList->map(function ($user) use ($cacheList, $today) {
            $key = "{$today}.{$user->id}";
            $user['cache_key'] = $key;
            $user['pre_dispatch_date'] = Cache::get($user->id . Administrator::$dispatchDateKey);
            $user["today_dispatch"] = Arr::get($cacheList, $key, 0);
            return $user;
        })->filter(function ($item) {
                return $item->full_dispatch_limit > $item["today_dispatch"];
            });

        return $data->sortBy('pre_dispatch_date')->first();
    }

    public static function getGroupDispatchUser($id)
    {
        if ($id && $model = static::find($id))
            return $model->dispatchOnlineUser();
        return null;
    }

}
